<?php 
/**
 * @author MarcusM. works for huike. QQ:2453302174
 */
class WxInterfaceHelper
{
	use BasicTrait;
	
	protected $_appid = null;
	protected $_appsecret = null;
	
	protected $_curl;
	protected function _cInit()
	{
		$this->_curl = curl_init();
		curl_setopt($this->_curl, CURLOPT_HTTPHEADER, array(
			"content-type: application/x-www-form-urlencoded; charset=UTF-8"
		));
		curl_setopt($this->_curl, CURLOPT_SSL_VERIFYHOST, 0);
		curl_setopt($this->_curl, CURLOPT_SSL_VERIFYPEER, 0);
		curl_setopt($this->_curl, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($this->_curl, CURLOPT_CONNECTTIMEOUT_MS, 5000);
		curl_setopt($this->_curl, CURLOPT_TIMEOUT_MS, 5000);
	}

	public function __construct($appid, $appsecret)
	{
		$this->init($appid, $appsecret);
	}
	public function __destruct()
	{
		curl_close($this->_curl);
	}
	
	public function redisSet($key, $value)
	{
		$key = 'WxInterfaceHelper:' . $key;
		return app()->redis->set($key, $value);
	}
	
	public function redisSetex($key, $timeout, $value)
	{
		$key = 'WxInterfaceHelper:' . $key;
		return app()->redis->setex($key, $timeout, $value);
	}
	
	public function redisGet($key)
	{
		$key = 'WxInterfaceHelper:' . $key;
		return app()->redis->get($key);
	}
	
	public function init($appid, $appsecret)
	{
		$this->_cInit();
		$this->appInit($appid, $appsecret);
	}
	
	public function appInit($appid, $app_secret)
	{
		$this->_appid = $appid;
		$this->_appsecret = $app_secret;
	}
	
	protected function _runCurl($baseReq, $reqFields)
	{
		$url = empty($reqFields)? $baseReq : $baseReq . '?' . http_build_query($reqFields);
		curl_setopt($this->_curl, CURLOPT_URL, $url);
//		curl_setopt($this->_curl, CURLOPT_POSTFIELDS, $reqFields);
		$ret = curl_exec($this->_curl);
		
		return $ret;
	}
	
	protected function _runPostCurl($baseReq, $reqFields)
	{
		$url = $baseReq;
		curl_setopt($this->_curl, CURLOPT_URL, $url);
		curl_setopt($this->_curl, CURLOPT_POST, 1);
		curl_setopt($this->_curl, CURLOPT_POSTFIELDS, json_encode($reqFields, JSON_UNESCAPED_UNICODE));
		$ret = curl_exec($this->_curl);
		
		return $ret;
	}
	

	public function getOauth2AccessToken($code)
	{$refresh = true;
		$oauthAccessToken = $this->_runCurl('https://api.weixin.qq.com/sns/oauth2/access_token', array(
			'appid' => $this->_appid,
			'secret' => $this->_appsecret,
			'code' => $code,
			'grant_type' => 'authorization_code'
		));
		return json_decode($oauthAccessToken);
	}
	
	const CGIBIN_ACCESS_TOKEN_KEY_CACHE = 'CGIBIN_ACCESS_TOKEN_KEY_CACHE';

	public function getCgibinAccessToken($refresh = false)
	{
		$cachedKey = self::CGIBIN_ACCESS_TOKEN_KEY_CACHE . '.' . $this->_appid . '.' . $this->_appsecret;
		
		if($refresh || empty( ($accessToken = $this->redisGet($cachedKey)) )){

		    $send_data = array(
                'appid' => $this->_appid,
                'secret' => $this->_appsecret,
                'grant_type' => 'client_credential'
            );

			$accessToken = $this->_runCurl('https://api.weixin.qq.com/cgi-bin/token', $send_data);
			$accessTokenObj = json_decode($accessToken);
			$cacheTime = empty($accessTokenObj->expires_in)? 300 : $accessTokenObj->expires_in-600;
			$this->redisSetex($cachedKey, $cacheTime, $accessToken);
		}


		return json_decode($accessToken);
	}

    protected function _cgiTokenLog($info)
    {
        $log_file = dirname(__FILE__) . '/logs/cgi_token_ajx.log';

        $info = empty($info)? '' : $info;
        $info = date('Y-m-d H:i:s - ')  . 'java' . $info . "\n";

        $handler = fopen($log_file, 'a+');
        fputs($handler, $info);
        fclose($handler);
    }

	const CGIBIN_TICKET_KEY_CACHE = 'CGIBIN_TICKET_KEY_CACHE';
	public function getCgibinTicket($refresh = false)
	{$refresh = true;
		$cachedKey = self::CGIBIN_TICKET_KEY_CACHE . '.' . $this->_appid . '.' . $this->_appsecret;
		
		if($refresh || empty( ($ticket = $this->redisGet($cachedKey)) )){
			$cgiAccessToken = $this->getCgibinAccessToken()->access_token;
			$ticket = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$cgiAccessToken}&type=jsapi");
			$ticketObj = json_decode($ticket);
			
			$cacheTime = empty($accessTokenObj->expires_in)? 300 : $ticketObj->expires_in-1200;
			$this->redisSetex($cachedKey, $cacheTime, $ticket);
		}
		
		return json_decode($ticket);
	}
	
	const CARD_API_TICKET_KEY_CACHE = 'CARD_API_TICKET_KEY_CACHE';
	public function getCardApiTicket($refresh = false)
	{$refresh = true;
		$cachedKey = self::CARD_API_TICKET_KEY_CACHE . '.' . $this->_appid . '.' . $this->_appsecret;
	
		if($refresh || empty( ($ticket = $this->redisGet($cachedKey)) )){
			$cgiAccessToken = $this->getCgibinAccessToken()->access_token;
			$ticket = file_get_contents("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$cgiAccessToken}&type=wx_card");
			$ticketObj = json_decode($ticket);
			
			$cacheTime = empty($accessTokenObj->expires_in)? 300 : $ticketObj->expires_in-1200;
			$this->redisSetex($cachedKey, $cacheTime, $ticket);
		}
	
		return json_decode($ticket);
	}
	
	

}